// 获取设备信息
export function getsys() {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				console.log(err, "获取设备信息失败")
				reject(err)
			}
		});
	})
}

// 获取当前定位
export function getLocation(type = 'gcj02') {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: type,
			geocode: true,
			success: (res) => {
				console.log('获取的定位', res)
				resolve(res)
			},
			fail: (err) => {
				console.log("获取定位失败", err)
				reject(err)
			}
		})
	})
}

/**
 * Android权限查询
 * @param permissionID
 * android.permission.ACCESS_FINE_LOCATION    位置权限
 * android.permission.ACCESS_COARSE_LOCATION    模糊位置权限(蓝牙\ble依赖)
 * android.permission.CAMERA    摄像头权限
 * android.permission.READ_EXTERNAL_STORAGE    外部存储(含相册)读取权限
 * android.permission.WRITE_EXTERNAL_STORAGE    外部存储(含相册)写入权限
 * android.permission.RECORD_AUDIO    麦克风权限
 * android.permission.READ_CONTACTS    通讯录读取权限
 * android.permission.WRITE_CONTACTS    通讯录写入权限
 * android.permission.READ_CALENDAR    日历读取权限
 * android.permission.WRITE_CALENDAR    日历写入权限
 * android.permission.READ_SMS    短信读取权限
 * android.permission.SEND_SMS    短信发送权限
 * android.permission.RECEIVE_SMS    接收新短信权限
 * android.permission.READ_PHONE_STATE    获取手机识别码等信息的权限
 * android.permission.CALL_PHONE    拨打电话权限
 * android.permission.READ_CALL_LOG    获取通话记录权限
 * @return {Promise<unknown>}
 */
export function requestAndroidPermission(permissionID) {
	return new Promise((resolve, reject) => {
		plus.android.requestPermissions(
			permissionID, // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
			function(resultObj) {
				let result = 0;
				for (let i = 0; i < resultObj.granted.length; i++) {
					const grantedPermission = resultObj.granted[i];
					console.log('已获取的权限：' + grantedPermission);
					result = 1
				}
				for (let i = 0; i < resultObj.deniedPresent.length; i++) {
					const deniedPresentPermission = resultObj.deniedPresent[i];
					console.log('拒绝本次申请的权限：' + deniedPresentPermission);
					result = 0
				}
				for (let i = 0; i < resultObj.deniedAlways.length; i++) {
					const deniedAlwaysPermission = resultObj.deniedAlways[i];
					console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
					result = -1
				}
				resolve(result);
				//若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
				if (result != 1) {
					gotoAppPermissionSetting()
				}
			},
			function(error) {
				console.log('申请权限错误：' + error.code + " = " + error.message);
				resolve({
					code: error.code,
					message: error.message
				});
			}
		);
	});
}

/**
 * 跳转到设置权限页面
 */
export function gotoAppPermissionSetting() {
	const Intent = plus.android.importClass("android.content.Intent");
	const Settings = plus.android.importClass("android.provider.Settings");
	const Uri = plus.android.importClass("android.net.Uri");
	const mainActivity = plus.android.runtimeMainActivity();
	const intent = new Intent();
	intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
	const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
	intent.setData(uri);
	mainActivity.startActivity(intent);
}

// 获取wifi列表
export function wifiInit() {
	// 主窗体  
	let MainActivity = plus.android.runtimeMainActivity()
	// 上下文  
	let Context = plus.android.importClass('android.content.Context')
	// 导入WIFI管理 和 WIFI 信息 的class  
	plus.android.importClass("android.net.wifi.WifiManager")
	plus.android.importClass("android.net.wifi.WifiInfo")
	plus.android.importClass("android.net.wifi.ScanResult")
	plus.android.importClass("java.util.ArrayList")
	// 获取 WIFI 管理实例  
	let wifiManager = MainActivity.getSystemService(Context.WIFI_SERVICE)

	let resultList = wifiManager.getScanResults(),
		len = resultList.size()
	let arr = []
	for (let i = 0; i < len; i++) {
		// console.log(resultList.get(i).plusGetAttribute('SSID'),
		// 	resultList.get(i).plusGetAttribute('BSSID'),
		// 	resultList.get(i).plusGetAttribute('level'))
		if (resultList.get(i).plusGetAttribute('SSID')) {
			arr.push({
				mac: resultList.get(i).plusGetAttribute('BSSID'),
				ssid: resultList.get(i).plusGetAttribute('SSID'),
				rssi: resultList.get(i).plusGetAttribute('level'),
			})
		}

	}
	return arr;
}

// 搜索基站信息并返回数据
export function searchCellInfo() {
	var cellInfoList = plus.android.runtimeMainActivity().getSystemService("phone").getAllCellInfo();

	var cellData = [];
	for (var i = 0; i < cellInfoList.size(); i++) {
		var cell = cellInfoList.get(i);
		if (cell instanceof plus.android.importClass("android.telephony.CellInfoGsm")) {
			var cellIdentity = cell.getCellIdentity();
			var mcc = cellIdentity.getMcc();
			var mnc = cellIdentity.getMnc();
			var lac = cellIdentity.getLac();
			var cid = cellIdentity.getCid();
			var rssi = cell.getCellSignalStrength().getLevel();

			var cellInfo = {
				mcc: mcc,
				mnc: mnc,
				lac: lac,
				cid: cid,
				rssi: rssi
			};
			cellData.push(cellInfo);
		}
	}

	console.log("Cell Info:", cellData);

}

// 搜索蓝牙
export function searchDevices() {
	let main = plus.android.runtimeMainActivity();
	let Context = plus.android.importClass("android.content.Context");
	let BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
	plus.android.importClass(BManager); //引入相关的method函数
	let BAdapter = BManager.getAdapter();
	plus.android.importClass(BAdapter); //引入相关的method函数，这样之后才会有isEna
	let lists = BAdapter.getBondedDevices();
	plus.android.importClass(lists);
	let iterator = lists.iterator();
	plus.android.importClass(iterator);
	while (iterator.hasNext()) {
		let d = iterator.next();
		plus.android.importClass(d);
		console.log("名称：" + d.getName() + "，地址：" + d.getAddress());
		plus.bluetooth.getBLEDeviceRSSI({
			deviceId: d.getAddress(),
			success: function(e) {
				console.log('RSSI: ' + e.RSSI);
			},
			fail: function(e) {
				console.log('get RSSI failed: ' + JSON.stringify(e));
			}
		});
	}
}

// 获取时间
export function getCurrentDate() {
	let today = new Date();
	let year = today.getFullYear();
	let month = today.getMonth() + 1;
	let day = today.getDate();
	let hours = today.getHours();
	let minutes = today.getMinutes();
	let seconds = today.getSeconds();

	// 在月份、日期、小时、分钟、秒小于10时补0
	if (month < 10) {
		month = '0' + month;
	}
	if (day < 10) {
		day = '0' + day;
	}
	if (hours < 10) {
		hours = '0' + hours;
	}
	if (minutes < 10) {
		minutes = '0' + minutes;
	}
	if (seconds < 10) {
		seconds = '0' + seconds;
	}

	let formattedDateTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
	return formattedDateTime;
}

// 获取七天前的日期
export function getSevenDaysAgoDate() {
	// 获取当前日期
	let currentDate = new Date();

	// 计算7天前的日期
	let sevenDaysAgoDate = new Date(currentDate);
	sevenDaysAgoDate.setDate(currentDate.getDate() - 7);

	// 格式化日期为 yyyy-mm-dd hh:mm:ss
	let formattedDate =
		`${sevenDaysAgoDate.getFullYear()}-${(sevenDaysAgoDate.getMonth() + 1).toString().padStart(2, '0')}-${sevenDaysAgoDate.getDate().toString().padStart(2, '0')} ${sevenDaysAgoDate.getHours().toString().padStart(2, '0')}:${sevenDaysAgoDate.getMinutes().toString().padStart(2, '0')}:${sevenDaysAgoDate.getSeconds().toString().padStart(2, '0')}`;

	return formattedDate;
}

// 生成唯一ID
export function generateUniqueID() {
	let timestamp = new Date().getTime(); // 获取当前时间戳
	let randomNum = Math.floor(Math.random() * 1000); // 生成一个随机数

	let uniqueID = timestamp.toString() + randomNum.toString();
	return uniqueID;
}

// 逆编码
export function changeRegeo(longitude, latitude) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://restapi.amap.com/v3/geocode/regeo?parameters&location=${longitude},${latitude}&key=${'e89994266be0a3b6a43ef016ca6f8aa9'}`,
			method: "GET",
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// IP定位
export function ipLocation() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://restapi.amap.com/v3/ip?key=${'e89994266be0a3b6a43ef016ca6f8aa9'}`,
			method: "GET",
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 打开蓝牙
export function openBluetooth() {
	return new Promise((resolve, reject) => {
		uni.openBluetoothAdapter({
			success: (res) => {
				console.log("开启蓝牙成功", res)
				resolve(true)
			},
			fail: (err) => {
				console.error('开启接收蓝牙消息失败：', err)
				reject(false)
			}
		});
	})
}

// 打开WIFI
export function openNetwork() {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			complete: (res) => {
				resolve(res)
			}
		})
	})
}

// 判断手机GPS
export function getGEO_status() {
	let context = plus.android.importClass("android.content.Context");
	let locationManager = plus.android.importClass("android.location.LocationManager");
	let main = plus.android.runtimeMainActivity();
	let mainSvr = main.getSystemService(context.LOCATION_SERVICE);
	let status = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)
	return status ? 1 : 0
}